package api

// by daoyi
import (
	"fmt"
	"github.com/asaskevich/govalidator"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"simai_oa/model"
	"simai_oa/tool"
	"strconv"
)

// 定义一个GoodController结构体
type UserBasicController struct {
	BaseController // 继承BaseController
}

func (con UserBasicController) Home(c *gin.Context) {
	c.HTML(http.StatusOK, "chat/home.html", gin.H{
		"title": "home页",
	})
}

func (con UserBasicController) Login(c *gin.Context) {
	c.HTML(http.StatusOK, "chat/login.html", gin.H{
		"title": "登陆页",
	})
}

func (con UserBasicController) Register(c *gin.Context) {
	c.HTML(http.StatusOK, "chat/register.html", gin.H{
		"title": "登陆页",
	})
}

// UserLogin
// @Summary 用户登陆
// @Tags 前端-用户列表
// @param name query string false "用户名"
// @param password query string false "密码"
// @Success 200 {string} json{"code","message"}
// @Router /api/user/login [POST]
func (con UserBasicController) UserLogin(c *gin.Context) {

	//接收参数
	name := c.PostForm("name")
	//name1 := c.DefaultPostForm("name", "123456")
	password := c.PostForm("password")
	//name := c.Request.FormValue("name")
	//password := c.Request.FormValue("password")

	data := model.FindUserByName(name)
	if data.Name == "" {
		c.JSON(200, gin.H{
			"code":    2,
			"message": "用户名或密码不正确1！",
		})
		return
	}
	//验证用户密码是否正确
	err := tool.PasswordVerify(password, data.Password, data.Salt)
	//err == nil 验证正确
	if err != nil {
		c.JSON(200, gin.H{
			"code":    2,
			"message": "用户名或密码不正确2！",
		})
		return
	}
	// 使用jwt生成Token
	tokenString, err := tool.GenApiToken(data.ID, data.Name)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":     2,
			"err_info": "生成token错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code":    1,
		"token":   tokenString,
		"userId":  data.ID,
		"message": "用户登陆成功！",
	})
}

// Index
// @Summary 获取user信息
// @Tags 前端-用户列表
// @Success 200 {string} json{"code","message",data}
// @Router /api/user/index [GET]
func (con UserBasicController) Index(c *gin.Context) {

	//获取token中存的值
	token, _ := tool.GetTokenFromRequest(c)
	name := tool.GetValueFromTokenClaims("Name", token.Claims)
	fmt.Println(name)

	data := make([]*model.UserBasic, 10)
	data = model.GetUserList()

	c.JSON(200, gin.H{
		"code":    1,
		"message": "查询成功！",
		"data":    data,
	})
}

func modify(x []string, y map[string]int, x1 *[]string) {
	x[0] = "李白libai"
	y["age"] = 12
	*x1 = append(*x1, "as")
}

type person struct {
	name, addr string
	age        int
}

// GetAll
// @Summary 所有用户
// @Tags 前端-用户列表
// @Success 200 {string} json{"code","message","data"}
// @Router /api/user/getall [POST]

func (con UserBasicController) GetAll(c *gin.Context) {
	a := person{
		"libai",
		"shanghai",
		12,
	}
	b := &a
	a.name = "杜甫"
	fmt.Printf("%#v %v %p\n", a, a, &a)
	fmt.Printf("%#v %v %p\n", b, b, &b)
	// data := model.GetAll()
	data := []string{"jk"}
	data_y := map[string]int{}
	modify(data, data_y, &data)

	c.JSON(200, gin.H{
		"code":    1,
		"message": "查询成功！",
		"data":    data,
	})
}

// CreateUser
// @Summary 创建用户
// @Tags 前端-用户列表
// @param name query string false "用户名"
// @param password query string false "密码"
// @param repassword query string false "确认密码"
// @Success 200 {string} json{"code","message"}
// @Router /api/user/create [POST]
func (con UserBasicController) CreateUser(c *gin.Context) {
	user := model.UserBasic{}
	user.Name = c.PostForm("name")
	password := c.PostForm("password")
	repassword := c.PostForm("repassword")

	if user.Name == "" || password == "" {
		c.JSON(200, gin.H{
			"code":    2,
			"message": "用户名或密码不能为空！",
		})
		return
	}

	//判断用户名是否已存在
	data := model.FindUserByName(user.Name)
	if data.Name != "" {
		c.JSON(200, gin.H{
			"code":    2,
			"message": "此用户名已注册！",
		})
		return
	}
	if password != repassword {
		c.JSON(200, gin.H{
			"code":    2,
			"message": "两次密码不一致！",
		})
		return
	}
	//生成随机数，用MD5加密后得到密码
	salt := fmt.Sprintf("%06d", rand.Int31())
	user.Password = tool.MakePassword(password, salt)
	user.Salt = salt
	fmt.Println(user)
	//新增用户
	ok := model.CreateUser(user)
	if ok != nil {
		c.JSON(200, gin.H{
			"code":    2,
			"message": "db error",
		})
		return
	}
	c.JSON(200, gin.H{
		"code":    1,
		"message": "新增用户成功",
	})
}

// UpdateUser
// @Summary 更新用户
// @Tags 前端-用户列表
// @param id formData string false "用户id"
// @param name formData string false "用户名"
// @param password formData string false "密码"
// @param phone formData string false "手机号"
// @param email formData string false "邮箱"
// @Success 200 {string} json{"code","message"}
// @Router /api/user/update [POST]
func (con UserBasicController) UpdateUser(c *gin.Context) {
	user := model.UserBasic{}
	id, _ := strconv.Atoi(c.PostForm("id")) //转换成int类型
	user.ID = uint(id)                      //转换成uint类型
	user.Name = c.PostForm("name")
	user.Password = c.PostForm("password")
	user.Phone = c.PostForm("phone")
	user.Email = c.PostForm("email")

	//效验
	_, err := govalidator.ValidateStruct(user)
	if err != nil {
		c.JSON(200, gin.H{
			"code":    2,
			"message": err,
		})
		return
	}
	model.UpdateUser(user)
	c.JSON(200, gin.H{
		"code":    1,
		"message": "修改用户成功！",
	})
}

// DeleteUser
// @Summary 删除用户
// @Tags 前端-用户列表
// @param id query string false "用户id"
// @Success 200 {string} json{"code","message"}
// @Router /api/user/delete [GET]
func (con UserBasicController) DeleteUser(c *gin.Context) {
	user := model.UserBasic{}
	id, _ := strconv.Atoi(c.Query("id")) //转换成int类型
	user.ID = uint(id)                   //转换成uint类型
	model.DeleteUser(user)
	c.JSON(200, gin.H{
		"code":    1,
		"message": "删除用户成功！",
	})
}

func (con UserBasicController) SearchFriends(c *gin.Context) {
	//userId, _ := strconv.Atoi(c.PostForm("userId"))
	userId, _ := c.Get("Id")
	user := model.SearchFriend(userId)

	//c.JSON(200, gin.H{
	//	"code":    1,
	//	"message": "拉取好友列表成功！",
	//	"data":    user,
	//})
	tool.RespOkList(c.Writer, user, len(user))
}

// GetAllUserExportToWeb
// @Summary 获取所有用户数据-excel(导出到服务器D盘)
// @Tags 前端-用户列表
// @Router /api/user/toweb [GET]
func GetAllUserExportToWeb(ctx *gin.Context) {
	var users []model.Users
	db := tool.Gdb
	db.Find(&users)

	//定义首行标题
	dataKey := make([]map[string]string, 0)
	dataKey = append(dataKey, map[string]string{
		"key":    "id",
		"title":  "索引",
		"width":  "20",
		"is_num": "0",
	})
	dataKey = append(dataKey, map[string]string{
		"key":    "username",
		"title":  "用户名",
		"width":  "20",
		"is_num": "0",
	})
	dataKey = append(dataKey, map[string]string{
		"key":    "age",
		"title":  "年龄",
		"width":  "20",
		"is_num": "0",
	})

	dataKey = append(dataKey, map[string]string{
		"key":    "email",
		"title":  "电子邮箱",
		"width":  "20",
		"is_num": "0",
	})

	dataKey = append(dataKey, map[string]string{
		"key":    "age",
		"title":  "年龄",
		"width":  "20",
		"is_num": "0",
	})

	dataKey = append(dataKey, map[string]string{
		"key":    "create_time",
		"title":  "创建时间",
		"width":  "20",
		"is_num": "0",
	})

	//填充数据
	data := make([]map[string]interface{}, 0)
	if len(users) > 0 {
		for _, v := range users {
			data = append(data, map[string]interface{}{
				"id":          v.Id,
				"username":    v.Username,
				"age":         v.Age,
				"email":       v.Email,
				"create_time": v.CreateTime,
			})
		}
	}
	ex := tool.NewMyExcel()

	// ex.ExportToWeb(dataKey, data, ctx)

	//保存到D盘
	ex.ExportToPath(dataKey, data, "D:/")
}

// GetUserExcelByMap
// @Summary excel 导出
// @Tags 前端-用户列表
// @Router /api/user/export [GET]
func GetUserExcelByMap(ctx *gin.Context) {
	var users []model.Users
	db := tool.Gdb
	db.Find(&users)

	titles := []string{"ID", "用户名", "年龄", "电子邮箱", "创建时间"}

	ex := tool.NewMyExcel()

	var datas []interface{}
	for _, v := range users {
		//这里最好新建一个struct 和titles一致，不然users里面的多余的字段也会写进去
		datas = append(datas, model.Users{
			Id:         v.Id,
			Username:   v.Username,
			Age:        v.Age,
			Email:      v.Email,
			CreateTime: v.CreateTime,
		})
	}
	ex.ExportExcelByStruct(titles, datas, "用户数据", "用户", ctx)
}
